<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\DB;

class Visit extends BaseModel
{
    protected $table = "sys_visits";

    public static function createRecord($obj_id,$obj_type=1,$origin=0)
    {
        $v= new Visit();
        $v->user_id = auth()->user()?auth()->user()->id:0;
        $v->obj_id = $obj_id;
        $v->obj_type = $obj_type;
        $v->origin = $origin;
        $v->save();

        //$v->updateObj();
    }

    public function updateObj()
    {
        $a = [1=>'cms_article',2=>'wine_product'];

        if (isset($a[$this->obj_type]) &&  $a[$this->obj_type]) {
            DB::table($a[$this->obj_type])->where('id','=',$this->obj_id)->update([
                'pv' => $this->pv(),
                'uv' => $this->uv()
            ]);
        }

    }

    public function pv()
    {
        return DB::table($this->table)->where('obj_id','=',$this->obj_id)
            ->where('obj_type','=',$this->obj_type)
            ->count();
    }

    public function uv()
    {
        return DB::table($this->table)->where('obj_id','=',$this->obj_id)
            ->where('obj_type','=',$this->obj_type)
            ->where('user_id','<>',0)
            ->select('user_id')->get()->count();
    }
}
